package com.atguigu.day03;

import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.Collector;

import java.util.Random;

public class Example11 {
    public static void main(String[] args) {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new SensorSource())
                .keyBy(r -> r.sensorId)
                .process(new SensorAlert())
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 思路：
    //   - 定时器的作用：报警
    //   - 如果温度出现上升 且 没有注册过报警定时器，那么注册1s之后的定时器
    //   - 如果温度出现下降 且 已经注册过报警定时器，那么删除报警定时器
    //   - 需要使用状态变量将定时器的时间戳保存下来
    public static class SensorAlert extends KeyedProcessFunction<String, SensorReading, String> {
        private ValueState<Double> lastTemp; // 用来保存最近一次的温度
        private ValueState<Long> timerTs; // 用来保存报警定时器的时间戳

        @Override
        public void open(Configuration parameters) throws Exception {
            lastTemp = getRuntimeContext().getState(
                    new ValueStateDescriptor<>(
                            "last-temp",
                            Types.DOUBLE
                    )
            );
            timerTs = getRuntimeContext().getState(
                    new ValueStateDescriptor<>(
                            "timer-ts",
                            Types.LONG
                    )
            );
        }

        @Override
        public void processElement(SensorReading sensorReading, Context context, Collector<String> collector) throws Exception {
            // 首先取出上一次温度
            var prevTemp = lastTemp.value();
            // 将本次温度保存
            lastTemp.update(sensorReading.temperature);

            if (prevTemp != null) {
                // 如果温度出现上升 且 没有注册过报警定时器
                if (sensorReading.temperature > prevTemp && timerTs.value() == null) {
                    long currentTs = context.timerService().currentProcessingTime();
                    // 注册1s之后的定时器
                    context.timerService().registerProcessingTimeTimer(currentTs + 1000L);
                    // 保存定时器的时间戳
                    timerTs.update(currentTs + 1000L);
                }
                // 如果温度出现下降 且 已经注册过报警定时器
                else if (sensorReading.temperature < prevTemp && timerTs.value() != null) {
                    // 在定时器触发之前，删除定时器
                    context.timerService().deleteProcessingTimeTimer(timerTs.value());
                    // 清空timerTs
                    timerTs.clear();
                }
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            out.collect(ctx.getCurrentKey() + "连续1s温度上升");
            // 定时器触发之后也不存在了，所以也要清空timerTs
            timerTs.clear();
        }
    }

    public static class SensorSource implements SourceFunction<SensorReading> {
        private boolean running = true;
        private final Random random = new Random();
        @Override
        public void run(SourceContext<SensorReading> sourceContext) throws Exception {
            while (running) {
                for (int i = 1; i < 4; i++) {
                    sourceContext.collect(new SensorReading(
                            "sensor_" + i,
                            random.nextGaussian()
                    ));
                }

                Thread.sleep(300L);
            }
        }

        @Override
        public void cancel() {
            running = false;
        }
    }

    public static class SensorReading {
        public String sensorId;
        public Double temperature;

        public SensorReading() {
        }

        public SensorReading(String sensorId, Double temperature) {
            this.sensorId = sensorId;
            this.temperature = temperature;
        }

        @Override
        public String toString() {
            return "SensorReading{" +
                    "sensorId='" + sensorId + '\'' +
                    ", temperature=" + temperature +
                    '}';
        }
    }
}
